package com.bckj.fastboot.core.extra.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.bckj.fastboot.core.extra.easyexcel.exception.ExcelCheckException;
import com.bckj.fastboot.core.lang.exception.BusinessException;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Getter
public abstract class BaseReadListener<T, D> extends AnalysisEventListener<T> {

    private final List<D> dataList = new ArrayList<>();
    private final List<String> errorList = new ArrayList<>();

    public abstract void check(T t) throws ExcelCheckException;

    public abstract D convert(T t);

    public abstract void onHandle(D data);

    public boolean isFail() {
        return !errorList.isEmpty();
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        try {
            check(data);
        } catch (ExcelCheckException e) {
            log.error(e.getMessage(), e);
            int hang = context.readRowHolder().getRowIndex() + 1;
            errorList.add("row:" + hang + " error:" +e.getMessage());
        }
        dataList.add(convert(data));
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (isFail()) {
            throw new BusinessException("检查失败");
        }
        for (D data : dataList) {
            try {
                onHandle(data);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                errorList.add(e.getMessage());
            }
        }
    }
}
